package com.jdz.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.jdz.common.ServerResponse;
import com.jdz.dao.AnnouncemenMapper;
import com.jdz.dao.ExcellentWorksMapper;
import com.jdz.dao.ProjectDetailsMapper;
import com.jdz.pojo.Announcemen;
import com.jdz.pojo.ProjectDetails;
import com.jdz.service.IAnnouncemenService;
import com.jdz.util.DateTimeUtil;
import com.jdz.util.Html2Text;
import com.jdz.util.MyStringUtil;
import com.jdz.vo.ListAnnouncemeTopVo;
import com.jdz.vo.SearchIndexVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by sun
 **/
//TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();注解后可用的手动回滚
@Transactional
@Service("IAnnouncemenService")
public class AnnouncemenServiceImpl implements IAnnouncemenService {

    private Logger logger = LoggerFactory.getLogger(AnnouncemenServiceImpl.class);


    @Autowired
    AnnouncemenMapper announcemenMapper;
    @Autowired
    ExcellentWorksMapper excellentWorksMapper;
    @Autowired
    ProjectDetailsMapper projectDetailsMapper;

    public ServerResponse saveOrUpdateAnnouncemen(Announcemen announcemen) {



        if(announcemen != null)
        {
            announcemen.setTop(0);
            announcemen.setCreattime(new Date());
            if(announcemen.getAnnno() != null){

                int rowCount = announcemenMapper.updateByPrimaryKeySelective(announcemen);
                if(rowCount > 0){
                    return ServerResponse.createBySuccessMessage("更新公告成功");
                }
                return ServerResponse.createByErrorMessage("更新公告失败");
            }else{
                int rowCount = announcemenMapper.insertSelective(announcemen);
                if(rowCount > 0){
                    return ServerResponse.createBySuccessMessage("新增公告成功");
                }
                return ServerResponse.createByErrorMessage("新增公告失败");
            }
        }
        return ServerResponse.createByErrorMessage("新增或更新公告参数不正确");
    }

    public ServerResponse announcemenTop(List<Integer> annnoList){

        if(CollectionUtils.isEmpty(annnoList)){
            return ServerResponse.createByErrorMessage("未选择公告");
        }

        for(Integer annnoItem : annnoList){
            Announcemen announcemen = new Announcemen();
            announcemen.setAnnno(annnoItem);
            announcemen.setTop(1);
            int rowCount = announcemenMapper.updateByPrimaryKeySelective(announcemen);
            if(rowCount <= 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ServerResponse.createByErrorMessage("置顶失败");
            }
        }

        return ServerResponse.createBySuccessMessage("置顶成功");
    }


    public ServerResponse announcemenRemoveTop(List<Integer> annnoList){

        if(CollectionUtils.isEmpty(annnoList)){
            return ServerResponse.createByErrorMessage("未选择公告");
        }

        for(Integer annnoItem : annnoList){
            Announcemen announcemen = new Announcemen();
            announcemen.setAnnno(annnoItem);
            announcemen.setTop(0);
            int rowCount = announcemenMapper.updateByPrimaryKeySelective(announcemen);
            if(rowCount <= 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ServerResponse.createByErrorMessage("取消置顶失败");
            }
        }

        return ServerResponse.createBySuccessMessage("取消置顶成功");
    }


    public ServerResponse deleteAnnouncemen(List<Integer> annnoList) {

        if(CollectionUtils.isEmpty(annnoList)){
            return ServerResponse.createByErrorMessage("未选择公告");
        }

        for(Integer annnoItem : annnoList){
//            int rowCount = announcemenMapper.deleteByPrimaryKey(annnoItem);
//            if(rowCount <= 0){
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                return ServerResponse.createByErrorMessage("删除公告失败");
//            }
            Announcemen announcemen = new Announcemen();
            announcemen.setAnnno(annnoItem);
            announcemen.setTop(2);
            int rowCount = announcemenMapper.updateByPrimaryKeySelective(announcemen);
            if(rowCount <= 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ServerResponse.createByErrorMessage("删除公告失败");
            }
        }

        return ServerResponse.createBySuccessMessage("删除公告成功");

    }

    public ServerResponse listAnnouncemen(int pageNum, int pageSize) {


        //startPage--start
        //填充自己的sql查询逻辑
        //pageHelper-收尾
        PageHelper.startPage(pageNum,pageSize);
        List<Announcemen> announcemenList = announcemenMapper.selectListTop();

        if(CollectionUtils.isEmpty(announcemenList)){
            logger.info("未找到公告");
        }

        List<ListAnnouncemeTopVo> listAnnouncemeTopVos = Lists.newArrayList();
        for(Announcemen announcemenItem : announcemenList){

            ListAnnouncemeTopVo listAnnouncemeTopVo = assembleAnnouncemeListVo(announcemenItem);
            listAnnouncemeTopVos.add(listAnnouncemeTopVo);
        }
        PageInfo pageResult = new PageInfo(announcemenList);
        pageResult.setList(listAnnouncemeTopVos);



        return ServerResponse.createBySuccess("第"+pageNum+"页，共"+pageResult.getPages()+"页，"+pageResult.getTotal()+"条数据",pageResult);

    }



    private ListAnnouncemeTopVo assembleAnnouncemeListVo(Announcemen announcemen){
        ListAnnouncemeTopVo listAnnouncemeTopVo = new ListAnnouncemeTopVo();
        listAnnouncemeTopVo.setAnnno(announcemen.getAnnno());
        listAnnouncemeTopVo.setAnnid(announcemen.getAnnid());
        listAnnouncemeTopVo.setTop(announcemen.getTop());
        listAnnouncemeTopVo.setCreattime(DateTimeUtil.dateToStr(announcemen.getCreattime(),"yyyy-MM-dd HH:mm"));
        return listAnnouncemeTopVo;
    }

    public ServerResponse detailsAnnouncemen(Integer annno){
        Announcemen announcemen = announcemenMapper.selectByPrimaryKey(annno);
        if(announcemen==null){
            return ServerResponse.createByErrorMessage("找不到当前公告");
        }
        return  ServerResponse.createBySuccess(announcemen);
    }

    public ServerResponse searchAnnounceme(String name, int pageNum, int pageSize, int time_sort){
        PageHelper.startPage(pageNum,pageSize);

        List<Announcemen> announcemenList;

        if(StringUtils.isNotBlank(name)){
            name = new StringBuilder().append("%").append(name).append("%").toString();

            if(time_sort==0) {
                announcemenList = announcemenMapper.selectSearchAnnouncement(name);
            } else {
                announcemenList = announcemenMapper.selectSearchAnnouncementTimeSort(name);
            }
        }else {
            if(time_sort==0) {
                announcemenList = announcemenMapper.selectListTop();
            }else {
                announcemenList = announcemenMapper.selectListTopSort();
            }
        }



        if(CollectionUtils.isEmpty(announcemenList)){
            logger.info("未找到公告");
        }

        List<ListAnnouncemeTopVo> listAnnouncemeTopVos = Lists.newArrayList();
        for(Announcemen announcemenItem : announcemenList){

            ListAnnouncemeTopVo listAnnouncemeTopVo = assembleAnnouncemeListVo(announcemenItem);
            listAnnouncemeTopVos.add(listAnnouncemeTopVo);
        }
        PageInfo pageResult = new PageInfo(announcemenList);
        pageResult.setList(listAnnouncemeTopVos);



        return ServerResponse.createBySuccess("第"+pageNum+"页，共"+pageResult.getPages()+"页，"+pageResult.getTotal()+"条数据",pageResult);
    }


    //portal
    public ServerResponse listUserAnnouncemen(int pageNum, int pageSize, String name, String startTime, String stopTime,int time_sort){

        PageHelper.startPage(pageNum,pageSize);


        Date startTimeDate;
        Date stopTimeDate;



        try {

            if(StringUtils.isBlank(startTime))
                startTimeDate=null;
            else
                startTimeDate = DateTimeUtil.dateMin(startTime);

            if(StringUtils.isBlank(name))
                name=null;
            else
                name = new StringBuilder().append("%").append(name).append("%").toString();

            if(StringUtils.isBlank(stopTime))
                stopTimeDate=null;
            else
                stopTimeDate = DateTimeUtil.dateMin(stopTime);


        }catch (Exception e){
            return ServerResponse.createByErrorMessage("列出公告列表参数格式错误");
        }


        //startPage--start
        //填充自己的sql查询逻辑
        //pageHelper-收尾
        PageHelper.startPage(pageNum,pageSize);
        List<Announcemen> announcemenList = null;
        if(time_sort == 0){
            announcemenList = announcemenMapper.selectListTopTime(name,startTimeDate,stopTimeDate);
        }else {
            announcemenList = announcemenMapper.selectListTopTimeSort(name,startTimeDate,stopTimeDate);
        }


        if(CollectionUtils.isEmpty(announcemenList)){
            logger.info("未找到公告");
        }

        List<ListAnnouncemeTopVo> listAnnouncemeTopVos = Lists.newArrayList();
        for(Announcemen announcemenItem : announcemenList){

            ListAnnouncemeTopVo listAnnouncemeTopVo = assembleAnnouncemeListVo(announcemenItem);
            listAnnouncemeTopVos.add(listAnnouncemeTopVo);
        }
        PageInfo pageResult = new PageInfo(announcemenList);
        pageResult.setList(listAnnouncemeTopVos);



        return ServerResponse.createBySuccess("第"+pageNum+"页，共"+pageResult.getPages()+"页，"+pageResult.getTotal()+"条数据",pageResult);
    }


    public ServerResponse search_index(String name) throws Exception {


        List<SearchIndexVo> searchIndexVoList = new ArrayList<>();

        String newName = null;

        try {
            if(StringUtils.isBlank(name))
                return ServerResponse.createByErrorMessage("参数为空");
            else
                newName = new StringBuilder().append("%").append(name).append("%").toString();
        }catch (Exception e){
            return ServerResponse.createByErrorMessage("列出公告列表参数格式错误");
        }

        List<Announcemen> announcemenList = announcemenMapper.selectSearchIndex(newName);

        if(!CollectionUtils.isEmpty(announcemenList)){
            for(Announcemen announcemenItem : announcemenList){

                SearchIndexVo searchIndexVo = new SearchIndexVo();
                String url = new StringBuilder().append("/noticeBoard.html").append("?annno=").append(announcemenItem.getAnnno()).toString();
                searchIndexVo.setUrl(url);
                searchIndexVo.setName(announcemenItem.getAnnid());



                String xiangqi;


                xiangqi = MyStringUtil.findtoSee(name, Html2Text.getHtmlToTest(announcemenItem.getAnndetail()));

                searchIndexVo.setXiangqin(xiangqi);

                if(Html2Text.getHtmlToTest(announcemenItem.getAnndetail()).indexOf(name)>=0 || announcemenItem.getAnnid().indexOf(name)>=0){
                    searchIndexVoList.add(searchIndexVo);
                }
            }
        }


        if(CollectionUtils.isEmpty(announcemenList)){
            logger.info("未找到公告");
        }


        List<Integer> excellentWorksList = excellentWorksMapper.seletAll();

        List<ProjectDetails> projectDetailsList = projectDetailsMapper.selectSearchIndex(newName);

        List<ProjectDetails> projectDetailsListrow = new ArrayList<>();

        for(ProjectDetails projectDetailsItem : projectDetailsList){
            for(Integer integerItem : excellentWorksList){
                if(integerItem.equals(projectDetailsItem.getProjectno())){
                    System.out.println(integerItem.equals(projectDetailsItem.getProjectno())+"========================");
                    projectDetailsListrow.add(projectDetailsItem);
                }
            }
        }


        if(!CollectionUtils.isEmpty(projectDetailsListrow)){
            for(ProjectDetails projectDetailsItem : projectDetailsListrow){

                SearchIndexVo searchIndexVo = new SearchIndexVo();
                String url = new StringBuilder().append("/look-item.html").append("?projectno=").append(projectDetailsItem.getProjectno()).toString();
                searchIndexVo.setUrl(url);
                searchIndexVo.setName(projectDetailsItem.getProjectname());


                String xiangqi;

                xiangqi = MyStringUtil.findtoSee(name, Html2Text.getHtmlToTest(projectDetailsItem.getProjectdetailed()));

                searchIndexVo.setXiangqin(xiangqi);

                if(Html2Text.getHtmlToTest(projectDetailsItem.getProjectdetailed()).indexOf(name)>=0 || projectDetailsItem.getProjectname().indexOf(name)>=0){
                    searchIndexVoList.add(searchIndexVo);
                }
            }
        }

        return ServerResponse.createBySuccess(searchIndexVoList);
    }
}
